package com.example.service.impl;

import com.example.domain.Role;
import com.example.domain.User;
import com.example.domain.UserRole;
import com.example.mapper.UserMapper;
import com.example.mapper.UserRoleMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public List<User> list(List<String> users) {
        return userMapper.list(users);
    }

    @Override
    public User getOne(String id) {
       return userMapper.getOne(id);
    }

    @Override
    @Transactional
    public void register(User user) {
        //检查数据库是否已存在这个邮箱与手机号
        int count = userMapper.emailCount(user.getEmail());
        int countPhone = userMapper.phoneCount(user.getPhone());
        if (count > 0){
            throw new RuntimeException("该邮箱已经注册");
        }
        if (countPhone > 0){
            throw new RuntimeException("手机号已存在");
        }
        //加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        user.setId(UUID.randomUUID().toString().replace("-",""));
        userMapper.register(user);
        //将用户添加至角色表
        User user1 = userMapper.getOneByEmail(user.getEmail());
        UserRole userRole = new UserRole();
        userRole.setId(UUID.randomUUID().toString().replace("-",""));
        userRole.setUserId(user1.getId());
        Role role = userRoleMapper.getRoleByName("用户");
        userRole.setRoleId(role.getId());
        userRoleMapper.addUserAndRole(userRole);
    }

    @Override
    public List<User> randomUser() {
        return userMapper.randomUser();
    }
}
